import React, { useMemo, useState } from 'react';
import { Spin, message } from 'antd';
import { isOriginSource } from '../utils';

/**
 * PDF 预览
 * 现代浏览器iframe会调用自身的PDF解析器去解析PDF文件
 */
const PDFPreview = ({ title, width = '100%', height = '100%', encode, visible, origin, onError }) => {
    const [loading, setLoading] = useState(false);

    const endLoading = () => {
        setLoading(false);
    };

    const previewUrl = useMemo(() => {
        const handleError = () => {
            const errorMsg = '资源加载失败!';
            if (onError) {
                onError(errorMsg);
            } else {
                message.error(errorMsg);
            }
            endLoading();
        };

        if (origin) {
            if (isOriginSource(origin)) {
                return encode ? encodeURIComponent(origin) : origin;
            }
            handleError();
        }
        return null;
    }, [encode, onError, origin]);

    return (
        previewUrl &&
        visible && (
            <>
                <iframe title={title} onLoad={endLoading} style={{ width, height, border: 0 }} src={previewUrl} />
                <Spin spinning={loading} />
            </>
        )
    );
};

export default PDFPreview;
